04. Select Page Element By ID

Select An Element By ID

Let's take a look at how we can use JavaScript and the DOM to gain access to specific elements using their ID attribute.

Remember the document object from the previous section? Well, we're going to start using it! Remember the document object is an object, just like a JavaScript object. This means it has key/value pairs. Some of the values are just pieces of data, while others are functions (also known as methods!) that provide some type of functionality. The first DOM method that we'll be looking at is the .getElementById() method:

document.getElementById();

If we ran the code above in the console, we wouldn't get anything, because we did not tell it the ID of any element to get! We need to pass a string to .getElementById() of the ID of the element that we want it to find and subsequently return to us:

document.getElementById('footer');

One thing to notice right off the bat, is that we're passing 'footer', not '#footer'. It already knows that it's searching for an ID (its name is "getElementById", for a reason!).

If you'd like to read more about this method, check out its documentation page on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

Let's use this MDN documentation page to try out using this method.

DOM L1 31 - Selecting The Content

To recap what we just did:

  • we opened the DevTools for the page we were looking at
  • we switched to the Console pane
  • we ran document.getElementById('content'); on the console

Running this code cause the document object to search through its entire tree-like structure for the element that has an ID of "content".

Task Description:

Now it's your turn!

Task List:

Task Feedback:

Fantastic work! That wasn't too hard, was it!

Now, what do you think will happen if you used document.getElementById(<some-nonexistent-ID>) to search for some ID that doesn't actually exist in the HTML page?

SOLUTION: `null` will be returned

DOM L1 35 - Looking At Returned Node

Which of the following will select the element with the ID of logo?

SOLUTION:
  • `document.getElementById('logo');`

QUESTION:

Write the DOM code to select the element with ID strawberry-banner.

SOLUTION:

NOTE: The solutions are expressed in RegEx pattern. Udacity uses these patterns to check the given answer

Selecting By ID Recap

In this section, we learned how to select a DOM element by its ID:

  • .getElementById()

There are a couple of important things to keep in mind about this method:

  • it is called on the document object
  • it returns a single item
// select the element with the ID "callout"
document.getElementById('callout');

Further Research